package com.homework.module6part3.controller;

import com.homework.dao.domain.User;
import com.homework.module6part3.service.UserService;
import com.homework.util.ResultMsg;
import com.homework.util.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
public class LoginController {

    @Autowired
    protected UserService userService;

    //登录页面
    @RequestMapping("/login")
    public ModelAndView login() {
        ModelAndView modelAndView = new ModelAndView("login");

        return modelAndView;
    }

    //执行登录
    @RequestMapping(value = "/dologin", method = {RequestMethod.POST})
    @ResponseBody
    public ResultMsg dologin(HttpServletRequest request, HttpServletResponse response) {
        String username= request.getParameter("username");
        String password= request.getParameter("password");

        User user = new User();
        user.setUsername(username);
        user.setPassword(password);

        User u = userService.getUser(user);
        if(u == null) {
            return ResultUtil.error(100, "错误的用户名/密码");
        }

        request.getSession().setAttribute("session_user", user);//登录成功后将用户放入session中，用于拦截
        return ResultUtil.success();
    }

}
